import React, { useEffect, useState, useRef } from "react";
import { Button } from "react-vant";
import axios from "axios";
import city from "../utils/city.json";

import { Fire } from "@react-vant/icons";
import IndexBars from "../components/IndexBars";
import { useNavigate } from "react-router-dom";
type Props = {};

const End = (props: Props) => {
  const [endData, setEndData] = useState([]);
  const navigate = useNavigate();
  const [cityList, setCityList] = useState(city.cityList);

  const valInp: any = useRef();
  const [cityVal, setCityVal] = useState("");
  useEffect(() => {
    (async () => {
      let res = await axios.get(
        "https://m.ly.com/trainbffapi/searchHotCity?mid=&pid=432&refId=478807627&traceId=T16819950604922841&ts=1681995076409&ver=1.0.0&abtkey=89d052c7-473a-4cd1-b1ae-b683984693b7&section=20&selectCity=1"
      );
      setEndData(res.data.data.result);
    })();
  }, []);
  //进页面被选择的城市高亮
  const [val, setVal] = useState(localStorage.getItem("end") || "");
  const [i, setI] = useState("");
  useEffect(() => {
    endData.forEach((item: any, index: any) => {
      if (item.name === val) {
        setI(index);
      }
    });
  }, [endData]);
  //点击城市存储
  const btnEnd = (name: any) => {
    localStorage.setItem("end", name);
    navigate("/index/home");
  };
  //inp
  const inpChange = (e: any) => {
    setCityVal(e.target.value);
  };
  //搜索
  const btnSearch = () => {
    console.log(123);
    const arr1 = endData.filter((item: any) => {
      return item.name.includes(cityVal);
    });
    setEndData(arr1);
  };
  return (
    <div>
      <div className="end">
        <header>
          <input ref={valInp} type={"text"} onChange={inpChange} />
          <Button onClick={btnSearch} type="primary">
            搜索
          </Button>
        </header>
        <main>
          <div style={{ width: "100%", height: "30px" }}></div>
          <div className="title">
            <Fire color="red" />
            <span>热门城市</span>
            <Fire color="red" />
          </div>
          <div className="city_box">
            {endData &&
              endData.map((item: any, index: any) => {
                return (
                  <span
                    className={i === index ? "on" : ""}
                    onClick={() => btnEnd(item.name)}
                    key={index}
                  >
                    {item.name}
                  </span>
                );
              })}
          </div>
          <div className="box">
            <IndexBars cityList={cityList} flag={false} />
          </div>
        </main>
      </div>
    </div>
  );
};

export default End;
